#include "paral_py.h"
#include "input_paral_fun_MR.h"
#include "paral_py_ast.h"

// 针对某个函数进行转换，参数为函数名
// 将普通函数进行转换
std::string trans_seq_to_def(struct paral_py_context *ctx, std::string seq_fun_name)
{
    // 首先取出来
    // 查看要读取的数据在不在
    if (ctx->fun_table.count(seq_fun_name) == 0)
    {
        printf("trans_seq_to_def:function:%s is not declare\n", seq_fun_name.c_str());
        return "";
    }

    // 从中读出数据
    struct function_table_item item = ctx->fun_table[seq_fun_name];

    if (item.function_type != tok_seq_def_type && item.function_type != tok_seq_comm_assoca_def_type)
    {
        printf("function is not seq\n");
        return "";
    }

    std::string return_str = get_code_by_line(ctx->file_name,
                                              item.function_begin_line, item.function_end_line);

    if (item.function_type == tok_seq_def_type)
    {

        return_str = return_str.replace(return_str.find("seq_def"),
                                        std::string("seq_def").length(), "def");
    }
    else
    {
        return_str = return_str.replace(return_str.find("seq_comm_assoca_def"),
                                        std::string("seq_comm_assoca_def").length(), "def");
    }

    return return_str;
}

// 针对input为中心的并行进行初步分析，返回是否可以进行转换
// result对应的操作是什么。这个分析是针对MR的
struct pre_process_report input_paral_pre_analysis(struct paral_py_context* ctx,
                                                   std::string function_name)
{
    
    struct pre_process_report report;
    report.can_trans = false;
    report.op_str = "";

    // 用一个变量存一下result变量的名称
    std::string result_name = "";

    // 用一个变量按顺序存一下表达式中的所有语元
    std::vector<struct paral_py_tok_basic_info> token_of_a_code_line;
    // 存所有代码的
    std::vector<std::vector<struct paral_py_tok_basic_info>> all_code_token;

    // 先找到对应的函数
    if (ctx->fun_table.count(function_name) == 0)
    {
        printf("input_paral_pre_analysis:function:%s is not declare\n", function_name.c_str());
        return report;
    }

    // 读出数据
    struct function_table_item item = ctx->fun_table[function_name];

    // 将函数的string取出
    std::string paral_code = get_code_by_line(ctx->file_name, item.function_begin_line, item.function_end_line);

    // 创建paral的分析
    struct input_paral_MR_context mr_ctx;
    init_input_paral_MR_context(&mr_ctx, paral_code, ctx);

    // 使用一个循环分析所有token
    int token_id = get_token_of_input_paral_fun_MR(&mr_ctx);

    std::stack<std::string> state_stack;


    // 一共三种状态，一个是函数声明合法性的表述
    // function->param
    // 一个是tab、item、等号三个东西不能连在一起
    // 还有tab、result、等号之后，左边的result要和右边的result保持一致
    // 或者右边没有Result
    state_stack.push("begin");

    

    // while(token_id != paral_py_language_tok_eof && token_id != paral_py_language_tok_unknow){
    while(token_id != paral_py_language_tok_unknow){    
        // 针对line状态，我们需要区分出表达式、if、while、else，for，以及他们与表达式之间的组合
        if(state_stack.top() == "code_line"){
            // codeline识别一行行代码每次碰到一个回车或者eof就打印一下
            // eof要注意直接退出分析程序
            if(token_id == paral_py_language_tok_tab){
                // 打印，然后清空
                // print_paral_py_express_token_arr(token_of_a_code_line);
                all_code_token.push_back(token_of_a_code_line);
                token_of_a_code_line.clear();

                token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
                continue;
            }

            if(token_id == paral_py_language_tok_eof){
                // print_paral_py_express_token_arr(token_of_a_code_line);
                all_code_token.push_back(token_of_a_code_line);
                token_of_a_code_line.clear();

                token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
                break;
            }

            // 剩下的情况收到数组中
            struct paral_py_tok_basic_info info;
            info.paral_py_token_type = token_id;
            info.tok_str = mr_ctx.identifier_str;
            token_of_a_code_line.push_back(info);
            token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
            continue;
        }

        // 首先针对begin状态
        if(state_stack.top() == "begin"){
            // 先处理function的声明
            if(token_id == paral_py_language_tok_gramma && mr_ctx.identifier_str == "input_central_paral"){
                // 进入function状态
                state_stack.push("function");
                token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
                continue;
            }

            // 遇到tab就进入代码一行代码识别状态
            if(token_id == paral_py_language_tok_tab){
                if(mr_ctx.tab_size <= 0){
                    printf("illegal tab size\n");
                    exit(-1);
                }else{
                    state_stack.push("code_line");
                    token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
                    continue;   
                }
            }

            // 解析不出来，不合法
            printf("illegal function declare\n");
            print_token_of_input_paral_fun_MR(token_id);
            exit(-1);
        }

        // 针对function状态
        if(state_stack.top() == "function"){
            // 一种是碰到op，一种是碰到括号，其他都是错误
            if(token_id == paral_py_language_tok_op){
                
                // 保证算子类型
                if(mr_ctx.fun_table.count(mr_ctx.identifier_str)){
                    struct function_table_item item;
                    memset(&item, 0, sizeof(struct function_table_item));

                    item = mr_ctx.fun_table[mr_ctx.identifier_str];

                    if(item.function_type != tok_input_central_paral_type){
                        printf("disable to tanslate to MR\n");
                        return report;
                    }
                }else{
                    printf("function is not found\n");
                    exit(-1);
                }

                token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
                continue;
            }

            // 碰到括号
            if(token_id == paral_py_language_tok_gramma){
                if(mr_ctx.identifier_str == "("){
                    state_stack.push("param");
                    token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
                    continue;
                }else if(mr_ctx.identifier_str == ":"){
                    state_stack.pop();
                    token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
                    continue;
                }

                printf("illegal function declare\n");
                exit(-1);
                
            }
        }

        // 处理函数参数
        if(state_stack.top() == "param"){
            // 碰到标记符只能是share和item
            if(token_id == paral_py_language_tok_var){
                if(mr_ctx.identifier_str != "item" && mr_ctx.identifier_str != "share"){
                    // 不合法
                    printf("illegal parameter\n");
                    exit(-1);
                }

                // 合法的
                token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
                continue;
            }

            // 剩下只能是逗号和右括号
            if(token_id == paral_py_language_tok_gramma){
                if(mr_ctx.identifier_str == ","){
                    token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
                    continue;
                }

                if(mr_ctx.identifier_str == ")"){
                    // 退出状态
                    state_stack.pop();
                    token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
                    continue;
                }

                // 到这里说明不合法
                printf("illegal parameter\n");
                exit(-1);
            }
        }

        std::cout << "当前状态" << state_stack.top() << std::endl;
        break;
        
    }

    if(token_id == paral_py_language_tok_unknow){
        printf("find unknow token\n");
        // std::cout << "当前状态" << state_stack.top() << std::endl;
        exit(-1);
    }

    // // 打印所有的token
    // int i;
    // for(i = 0; i < all_code_token.size(); i++){
    //     print_paral_py_express_token_arr(all_code_token[i]);
    // }

    report = input_paral_pre_analysis(all_code_token);

    int i;
    for(i = 0; i < all_code_token.size(); i++){
        print_paral_py_express_token_arr(all_code_token[i]);
    }
    
    // 以下嵌入一个测试代码

    // struct ast_tree_construct_context ast_ctx;
    
    // init_ast_tree_construct_context(&ast_ctx, all_code_token[0]);

    // // 预处理
    // ast_tree_construct_prepare(&ast_ctx);

    // print_paral_py_express_token_arr(ast_ctx.expression);

    // ast_tree_construct(&ast_ctx);

    
    // print_ast_tree(ast_ctx.tree_root);

    // std::cout << trans_ast_to_str(ast_ctx.tree_root) << std::endl;
    

    // 以上嵌入一个测试代码

    // 这里检查一下op的类型是什么
    // 首先检查op有没有
    if (report.op_str != "None")
    {
        if (ctx->fun_table.count(report.op_str) > 0)
        {
            struct function_table_item item;
            item = ctx->fun_table[report.op_str];
            if (item.function_type != tok_seq_comm_assoca_def_type)
            {
                std::cout << "op can't be used in MR" << std::endl;
                report.can_trans = false;
            }
        }
        else
        {
            std::cout << "cannot find op" << std::endl;
            report.can_trans = false;
        }

        if (report.can_trans == true)
        {
            std::cout << "find op:" << report.op_str << std::endl;
        }
    }else{
        if (report.can_trans == true)
        {
            std::cout << "find op:" << report.op_str << std::endl;
        }
    }

    // 将代码带入，返回报告
    return report;
}

// 将一整个函数转化为串行代码，主要针对if，while，else这几个的处理
// 主要针对map的处理
std::string input_paral_translate_to_MR_map(struct paral_py_context* ctx, std::string function_name){
    
    // 先找到对应的函数
    if (ctx->fun_table.count(function_name) == 0)
    {
        printf("input_paral_translate_to_MR_map:function:%s is not declare\n", function_name.c_str());
        return "";
    }

    // 读出数据
    struct function_table_item item = ctx->fun_table[function_name];

    // 将函数的string取出
    std::string paral_code = get_code_by_line(ctx->file_name, item.function_begin_line, item.function_end_line);
    
    // return 
    std::string return_str = "";

    // 创建paral的分析
    struct input_paral_MR_context mr_ctx;
    init_input_paral_MR_context(&mr_ctx, paral_code, ctx);

    // 使用一个循环分析所有token
    int token_id = get_token_of_input_paral_fun_MR(&mr_ctx);

    // 到eof停止
    while(token_id != paral_py_language_tok_eof){
        // 首先处理第一行
        if(token_id == paral_py_language_tok_gramma && mr_ctx.identifier_str == "input_central_paral"){
            // 遍历这一行
            while(token_id != paral_py_language_tok_tab){
                token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
            }

            // 这里一行结束了，输出for的一行
            return_str = return_str + "for line1357 in sys.stdin:\n\t";
            // 加一行代码初始化item
            return_str = return_str + "line1357 = line1357.strip()\n\t";
            return_str = return_str + "item.key = json.loads(line1357.split(\"\\t\")[0])\n\t";
            return_str = return_str + "item.value = json.loads(line1357.split(\"\\t\")[1])\n\t";
            continue;
        }

        // 碰到if，碰到while
        // if express:
        if(token_id == paral_py_language_tok_gramma && (mr_ctx.identifier_str == "if" || mr_ctx.identifier_str == "while")){
            
            // 首先打印if和while
            return_str = return_str + mr_ctx.identifier_str + " ";
            // 将剩下的内容
            token_id = get_token_of_input_paral_fun_MR(&mr_ctx);

            // 一个数组存express
            std::vector<struct paral_py_tok_basic_info> expression;
            
            while(mr_ctx.identifier_str != ":"){
                struct paral_py_tok_basic_info info;
                info.paral_py_token_type = token_id;
                info.tok_str = mr_ctx.identifier_str;

                expression.push_back(info);
                token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
            }

            
            struct ast_tree_construct_context ast_ctx;

            init_ast_tree_construct_context(&ast_ctx, expression);

            ast_tree_construct_prepare(&ast_ctx);
            ast_tree_construct(&ast_ctx);
            
            return_str = return_str + trans_ast_to_str(ast_ctx.tree_root);
        }



        // 碰到括号和var
        if(mr_ctx.identifier_str == "(" || token_id == paral_py_language_tok_var){
            
            
            std::vector<struct paral_py_tok_basic_info> expression;
            // 遍历这一行的内容，全部收集起来
            while(token_id != paral_py_language_tok_tab){
                struct paral_py_tok_basic_info info;
                info.paral_py_token_type = token_id;
                info.tok_str = mr_ctx.identifier_str;

                expression.push_back(info);
                token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
            }

            // 只有这里可能有result的赋值
            std::string related_to_result_code = "";

            // 初始化一个ast
            struct ast_tree_construct_context ast_ctx;

            init_ast_tree_construct_context(&ast_ctx, expression);

            if(ast_ctx.related_to_result_assign == true){
                // 首先将key提取出来
                std::string key_str = get_key_str_of_result(expression[0].tok_str);
                return_str = return_str + expression[0].tok_str + expression[1].tok_str;
                // 删除expression的头两个元素
                expression.erase(expression.begin(), expression.begin()+2);
                // 初始化一个ast
                struct ast_tree_construct_context ast_ctx_not_empty;
                init_ast_tree_construct_context(&ast_ctx_not_empty, expression);

                ast_tree_construct_prepare(&ast_ctx_not_empty);
                ast_tree_construct(&ast_ctx_not_empty);

                return_str = return_str + "(";
                return_str = return_str + trans_ast_to_str(ast_ctx_not_empty.tree_root);
                return_str = return_str + ") if (" + key_str + " in result ) else (";

                // 将expression中result和最近的一个操作符去掉
                if(expression.size()>=3){
                    int j;
                    for(j = 0; j < expression.size(); j++){
                        if(expression[j].tok_str.find("result[")==0){
                            // 看前后
                            if(j == expression.size() - 1){
                                // 最后一位就和前面的一起去掉
                                expression.erase(expression.begin() + j - 1, expression.begin() + j + 1);
                            }else{
                                // 删当前和后面
                                expression.erase(expression.begin() + j, expression.begin() + j + 2);
                            }
                        }
                    }
                    
                }

                struct ast_tree_construct_context ast_ctx_empty;
                init_ast_tree_construct_context(&ast_ctx_empty, expression);

                ast_tree_construct_prepare(&ast_ctx_empty);
                ast_tree_construct(&ast_ctx_empty);

                return_str = return_str + trans_ast_to_str(ast_ctx_empty.tree_root);
                

                return_str = return_str + ")";
            }else{
                //与赋值无关就正常处理
                ast_tree_construct_prepare(&ast_ctx);
                ast_tree_construct(&ast_ctx);
                return_str = return_str + trans_ast_to_str(ast_ctx.tree_root);
            }

        }

        // 碰到for循环
        // for express in express2:
        if(mr_ctx.identifier_str == "for"){
            

            // 首先打印for
            return_str = return_str + mr_ctx.identifier_str + " ";
            // 收集express
            token_id = get_token_of_input_paral_fun_MR(&mr_ctx);

            // 一个数组存express
            std::vector<struct paral_py_tok_basic_info> expression;
            
            while(mr_ctx.identifier_str != "in"){
                struct paral_py_tok_basic_info info;
                info.paral_py_token_type = token_id;
                info.tok_str = mr_ctx.identifier_str;

                expression.push_back(info);
                token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
            }

            // 初始化一个ast
            struct ast_tree_construct_context ast_ctx;

            init_ast_tree_construct_context(&ast_ctx, expression);
            ast_tree_construct_prepare(&ast_ctx);
            ast_tree_construct(&ast_ctx);
            return_str = return_str + trans_ast_to_str(ast_ctx.tree_root);
            

            // 打印in
            return_str = return_str + " " + mr_ctx.identifier_str + " ";

            // 收集express2
            token_id = get_token_of_input_paral_fun_MR(&mr_ctx);

            std::vector<struct paral_py_tok_basic_info> expression2;
            
            while(mr_ctx.identifier_str != ":"){
                struct paral_py_tok_basic_info info;
                info.paral_py_token_type = token_id;
                info.tok_str = mr_ctx.identifier_str;

                expression2.push_back(info);
                token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
            }

            // 初始化一个ast
            struct ast_tree_construct_context ast_ctx2;

            // 临时打印一个
            
            // print_paral_py_express_token_arr(expression2);


            init_ast_tree_construct_context(&ast_ctx2, expression2);
            ast_tree_construct_prepare(&ast_ctx2);
            ast_tree_construct(&ast_ctx2);
            return_str = return_str + trans_ast_to_str(ast_ctx2.tree_root);
        }


        // 碰到tab
        if(token_id == paral_py_language_tok_tab){
            
            // 首先回车
            return_str = return_str + "\n";
            int i;
            for(i = 0; i < mr_ctx.tab_size; i++){
                return_str = return_str + "\t";
            }
            // 下一个
            token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
            continue;
        }


        // 碰到剩下的就直接打印
        return_str = return_str + mr_ctx.identifier_str;
        token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
    }

    // 在尾巴上加一段代码
    return_str = return_str + "for key, value in result.items():\n\t";
    return_str = return_str + "sys.stdout.write(\"%s\\t%s\\n\" % (json.dumps(key), json.dumps(value)))";

    return return_str;
    
}

// 生成Reduce程序
void build_reduce_file(struct paral_py_context* ctx, std::string function_name, struct pre_process_report report){
    if(report.can_trans == false || report.op_str == "None"){
        printf("do not need reduce\n");
    }

    // 首先执行import
    // 文件删除
    remove((function_name + "_reducer.py").c_str());
    
    // 开始写入文件
    std::ofstream outfile;

    outfile.open((function_name + "_reducer.py"));

    // 首先写import sys 和 json
    outfile << "import sys" << std::endl;
    outfile << "import json" << std::endl;

    // 然后打印用户的import
    int i;
    for(i = 0; i < ctx->import_code_str_arr.size(); i++){
        outfile << ctx->import_code_str_arr[i] << std::endl;
    }

    outfile << std::endl;

    outfile << trans_seq_to_def(ctx, report.op_str) << std::endl;

    // 加入result的声明
    outfile << "result = {}" << std::endl;
    outfile << "lastKey = False" << std::endl;

    // 加入for的声明
    outfile << "for line123321 in sys.stdin:\n\t";

    outfile << "line123321 = line123321.strip()\n\t";
    outfile << "key = json.loads(line123321.split(\"\\t\")[0])\n\t";
    outfile << "value = json.loads(line123321.split(\"\\t\")[1])\n\t";

    outfile << "if lastKey and key !=lastKey:\n\t\t";
    outfile << "sys.stdout.write(\"%s\\t%s\\n\" % (json.dumps(lastKey), json.dumps(result[lastKey])))\n\t\t";
    outfile << "lastKey = key\n\t\t";

    // 这里执行真正的内容
    outfile << "result[key]=(" + report.op_str + "(result[key], value)) if (key in result ) else (value)\n\t";
    outfile << "else:\n\t\t";
    outfile << "lastKey = key\n\t\t";
    outfile << "result[key]=(" + report.op_str + "(result[key], value)) if (key in result ) else (value)\n";
    outfile << "if lastKey:\n\t";
    outfile << "sys.stdout.write(\"%s\\t%s\\n\" % (json.dumps(lastKey), json.dumps(result[lastKey])))\n\t\t";

    outfile << std::endl;
}



void build_mapper_reducer_file(struct paral_py_context* ctx, std::vector<std::string> seqs, std::string function_name){
    // 输出文件名和并行函数名一样
    scan_all_function(ctx);

    // 查看要并行的函数
    if(ctx->fun_table.count(function_name) == 0){
        printf("function is not found\n");
        return;
    }

    // 文件删除
    remove((function_name + "_mapper.py").c_str());

    // 开始写入文件
    std::ofstream outfile;

    outfile.open((function_name + "_mapper.py"));

    // 首先写import sys 和 json
    outfile << "import sys" << std::endl;
    outfile << "import json" << std::endl;

    // 然后打印用户的import
    int i;
    for(i = 0; i < ctx->import_code_str_arr.size(); i++){
        outfile << ctx->import_code_str_arr[i] << std::endl;
    }

    outfile << std::endl;

    // 打印所有的串行函数
    for(i = 0; i < seqs.size(); i++){
        if(ctx->fun_table.count(seqs[i])){
            outfile << trans_seq_to_def(ctx, seqs[i]) << std::endl;
        }else{
            // 找到
            printf("seq function is not found\n");
            return;
        }
    }

    outfile << std::endl;

    // 声明class
    outfile << "class ItemClass:\n\t";
    outfile << "def __init__(self):\n\t\t";
    outfile << "self.key = None\n\t\t";
    outfile << "self.value = None\n";

    outfile << std::endl;

    outfile << "item = ItemClass()" << std::endl;

    outfile << "result = {}" << std::endl;

    // 转并行代码
    struct pre_process_report report;
    report = input_paral_pre_analysis(ctx, function_name);

    if(report.can_trans == false){
        printf("cannot translate to MR\n");
        outfile.close();
        return;
    }

    outfile << std::endl;

    outfile << input_paral_translate_to_MR_map(ctx, function_name) << std::endl;

    outfile.close();

    if(report.op_str != "None"){
        build_reduce_file(ctx, function_name, report);
    }
}


void build_local_seq_file(struct paral_py_context* ctx, std::vector<std::string> seqs, std::string function_name){
    // 输出文件名和运行函数名一样
    scan_all_function(ctx);
    
    // 查看要运行的函数
    if(ctx->fun_table.count(function_name) == 0){
        printf("function is not found\n");
        return;
    }

    // 文件删除
    remove((function_name + "_local_seq.py").c_str());

    // 开始写入文件
    std::ofstream outfile;

    outfile.open((function_name + "_local_seq.py"));

    // 首先写import json
    outfile << "import json" << std::endl;
    outfile << "import sys" << std::endl;

    // 然后打印用户的import
    int i;
    for(i = 0; i < ctx->import_code_str_arr.size(); i++){
        outfile << ctx->import_code_str_arr[i] << std::endl;
    }

    outfile << std::endl;

    // 打印所有的串行函数
    for(i = 0; i < seqs.size(); i++){
        if(ctx->fun_table.count(seqs[i])){
            outfile << trans_seq_to_def(ctx, seqs[i]) << std::endl;
        }else{
            // 找到
            printf("seq function is not found\n");
            return;
        }
    }

    outfile << std::endl;

    // 声明class
    outfile << "class ItemClass:\n\t";
    outfile << "def __init__(self):\n\t\t";
    outfile << "self.key = None\n\t\t";
    outfile << "self.value = None\n";

    outfile << std::endl;

    outfile << "item = ItemClass()" << std::endl;

    outfile << "result = {}" << std::endl;

    // 原封不动变成串行代码
    // 预处理
    input_paral_pre_analysis(ctx, function_name);

    // 代码转换
    outfile << std::endl;

    outfile << input_paral_translate_to_local_seq(ctx, function_name) << std::endl;

    outfile.close();
}

// 生成一个本地运行的python脚本，这个脚本有两个命令行参数，一个是输出文件，一个是输入文件
std::string input_paral_translate_to_local_seq(struct paral_py_context* ctx, std::string function_name){
    // 先找到对应的函数
    if (ctx->fun_table.count(function_name) == 0)
    {
        printf("input_paral_translate_to_local_seq:function:%s is not declare\n", function_name.c_str());
        return "";
    }

    // 读出数据
    struct function_table_item item = ctx->fun_table[function_name];

    // 将函数的string取出
    std::string paral_code = get_code_by_line(ctx->file_name, item.function_begin_line, item.function_end_line);
    
    // return 
    std::string return_str = "";

    // 创建paral的分析
    struct input_paral_MR_context mr_ctx;
    init_input_paral_MR_context(&mr_ctx, paral_code, ctx);

    // 使用一个循环分析所有token
    int token_id = get_token_of_input_paral_fun_MR(&mr_ctx);

    // 到eof停止
    while(token_id != paral_py_language_tok_eof){
        // 首先处理第一行
        if(token_id == paral_py_language_tok_gramma && mr_ctx.identifier_str == "input_central_paral"){
            // 遍历这一行
            while(token_id != paral_py_language_tok_tab){
                token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
            }

            // 这里一行结束了，输出for的一行
            // 这里从文件读入，
            return_str = return_str + "for line1357 in open(sys.argv[1]):\n\t";
            // 加一行代码初始化item
            return_str = return_str + "line1357 = line1357.strip()\n\t";
            return_str = return_str + "item.key = json.loads(line1357.split(\"\\t\")[0])\n\t";
            return_str = return_str + "item.value = json.loads(line1357.split(\"\\t\")[1])\n\t";
            continue;
        }

        // 碰到if，碰到while
        // if express:
        if(token_id == paral_py_language_tok_gramma && (mr_ctx.identifier_str == "if" || mr_ctx.identifier_str == "while")){
            
            // 首先打印if和while
            return_str = return_str + mr_ctx.identifier_str + " ";
            // 将剩下的内容
            token_id = get_token_of_input_paral_fun_MR(&mr_ctx);

            // 一个数组存express
            std::vector<struct paral_py_tok_basic_info> expression;
            
            while(mr_ctx.identifier_str != ":"){
                struct paral_py_tok_basic_info info;
                info.paral_py_token_type = token_id;
                info.tok_str = mr_ctx.identifier_str;

                expression.push_back(info);
                token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
            }

            
            struct ast_tree_construct_context ast_ctx;

            init_ast_tree_construct_context(&ast_ctx, expression);

            ast_tree_construct_prepare(&ast_ctx);
            ast_tree_construct(&ast_ctx);
            
            return_str = return_str + trans_ast_to_str(ast_ctx.tree_root);
        }



        // 碰到括号和var
        if(mr_ctx.identifier_str == "(" || token_id == paral_py_language_tok_var){
            
            
            std::vector<struct paral_py_tok_basic_info> expression;
            // 遍历这一行的内容，全部收集起来
            while(token_id != paral_py_language_tok_tab){
                struct paral_py_tok_basic_info info;
                info.paral_py_token_type = token_id;
                info.tok_str = mr_ctx.identifier_str;

                expression.push_back(info);
                token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
            }

            // 只有这里可能有result的赋值
            std::string related_to_result_code = "";

            // 初始化一个ast
            struct ast_tree_construct_context ast_ctx;

            init_ast_tree_construct_context(&ast_ctx, expression);

            if(ast_ctx.related_to_result_assign == true){
                // 首先将key提取出来
                std::string key_str = get_key_str_of_result(expression[0].tok_str);
                return_str = return_str + expression[0].tok_str + expression[1].tok_str;
                // 删除expression的头两个元素
                expression.erase(expression.begin(), expression.begin()+2);
                // 初始化一个ast
                struct ast_tree_construct_context ast_ctx_not_empty;
                init_ast_tree_construct_context(&ast_ctx_not_empty, expression);

                ast_tree_construct_prepare(&ast_ctx_not_empty);
                ast_tree_construct(&ast_ctx_not_empty);

                return_str = return_str + "(";
                return_str = return_str + trans_ast_to_str(ast_ctx_not_empty.tree_root);
                return_str = return_str + ") if (" + key_str + " in result ) else (";

                // 将expression中result和最近的一个操作符去掉
                if(expression.size()>=3){
                    int j;
                    for(j = 0; j < expression.size(); j++){
                        if(expression[j].tok_str.find("result[")==0){
                            // 看前后
                            if(j == expression.size() - 1){
                                // 最后一位就和前面的一起去掉
                                expression.erase(expression.begin() + j - 1, expression.begin() + j + 1);
                            }else{
                                // 删当前和后面
                                expression.erase(expression.begin() + j, expression.begin() + j + 2);
                            }
                        }
                    }
                    
                }

                struct ast_tree_construct_context ast_ctx_empty;
                init_ast_tree_construct_context(&ast_ctx_empty, expression);

                ast_tree_construct_prepare(&ast_ctx_empty);
                ast_tree_construct(&ast_ctx_empty);

                return_str = return_str + trans_ast_to_str(ast_ctx_empty.tree_root);
                

                return_str = return_str + ")";
            }else{
                //与赋值无关就正常处理
                ast_tree_construct_prepare(&ast_ctx);
                ast_tree_construct(&ast_ctx);
                return_str = return_str + trans_ast_to_str(ast_ctx.tree_root);
            }

        }

        // 碰到for循环
        // for express in express2:
        if(mr_ctx.identifier_str == "for"){
            // 首先打印for
            return_str = return_str + mr_ctx.identifier_str + " ";
            // 收集express
            token_id = get_token_of_input_paral_fun_MR(&mr_ctx);

            // 一个数组存express
            std::vector<struct paral_py_tok_basic_info> expression;
            
            while(mr_ctx.identifier_str != "in"){
                struct paral_py_tok_basic_info info;
                info.paral_py_token_type = token_id;
                info.tok_str = mr_ctx.identifier_str;

                expression.push_back(info);
                token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
            }

            // 初始化一个ast
            struct ast_tree_construct_context ast_ctx;

            init_ast_tree_construct_context(&ast_ctx, expression);
            ast_tree_construct_prepare(&ast_ctx);
            ast_tree_construct(&ast_ctx);
            return_str = return_str + trans_ast_to_str(ast_ctx.tree_root);
            

            // 打印in
            return_str = return_str + " " + mr_ctx.identifier_str + " ";

            // 收集express2
            token_id = get_token_of_input_paral_fun_MR(&mr_ctx);

            std::vector<struct paral_py_tok_basic_info> expression2;
            
            while(mr_ctx.identifier_str != ":"){
                struct paral_py_tok_basic_info info;
                info.paral_py_token_type = token_id;
                info.tok_str = mr_ctx.identifier_str;

                expression2.push_back(info);
                token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
            }

            // 初始化一个ast
            struct ast_tree_construct_context ast_ctx2;

            init_ast_tree_construct_context(&ast_ctx2, expression2);
            ast_tree_construct_prepare(&ast_ctx2);
            ast_tree_construct(&ast_ctx2);
            return_str = return_str + trans_ast_to_str(ast_ctx2.tree_root);
        }


        // 碰到tab
        if(token_id == paral_py_language_tok_tab){
            
            // 首先回车
            return_str = return_str + "\n";
            int i;
            for(i = 0; i < mr_ctx.tab_size; i++){
                return_str = return_str + "\t";
            }
            // 下一个
            token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
            continue;
        }


        // 碰到剩下的就直接打印
        return_str = return_str + mr_ctx.identifier_str;
        token_id = get_token_of_input_paral_fun_MR(&mr_ctx);
    }

    return_str = return_str + "\n";

    // 在尾巴上加一段代码
    return_str = return_str + "outfile = open(sys.argv[2], \"w\")\n";
    return_str = return_str + "\n";
    return_str = return_str + "for key, value in result.items():\n\t";
    return_str = return_str + "outfile.write(\"%s\\t%s\\n\" % (json.dumps(key), json.dumps(value)))\n";
    return_str = return_str + "\n";

    // 关闭文件
    return_str = return_str + "outfile.close()\n";

    return return_str;
}